package me.zhengjie.modules.order.job;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.order.domain.OrderDetail;
import me.zhengjie.modules.order.domain.PayOrder;
import me.zhengjie.modules.order.mapper.OrderDetailMapper;
import me.zhengjie.modules.order.mapper.PayOrderMapper;
import me.zhengjie.modules.pay.enums.StatusEnum;
import me.zhengjie.modules.shop.domain.ProductKind;
import me.zhengjie.modules.shop.mapper.ProductKindMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static me.zhengjie.modules.biz.constant.GlobalConstant.SHOPPING_ORDER;
import static me.zhengjie.modules.pay.enums.StatusEnum.*;
import static me.zhengjie.modules.pay.enums.StatusEnum.AWAITCLOSED;
import static me.zhengjie.modules.pay.enums.StatusEnum.NOTPAY;

/**
 * 订单过期定时任务：更改订单状态，返还商品库存【一周内的订单都进行扫描】
 * @author yiwei.he
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class PayOrderExpireJob {

    private final PayOrderMapper payOrderMapper;

    private final ProductKindMapper productKindMapper;

    private final OrderDetailMapper orderDetailMapper;

    @Scheduled(cron = "0 */10 * * * *")
    @Transactional
    public void scheduleTask() {
        // 未支付 或者 待支付 的订单归还库存，修改状态为关闭

        List<PayOrder> payOrders = payOrderMapper.selectList(new QueryWrapper<PayOrder>()
                .and(qw -> qw.eq("trade_state", NOTPAY.getCode())
                        .or().eq("trade_state", AWAITCLOSED.getCode())
                        .or().eq("trade_state", ORDER_DEFAULT_STATUS.getCode()))
                .isNull("transaction_id")
                .eq("logistics_status", LOGISTICS_DEFAULT.getCode())
                .eq("sold_status", SOLD_DEFAULT.getCode())
                .lt("expire_time", LocalDateTime.now())
                .ge("create_time", LocalDateTime.now().minusWeeks(1)));
        log.info("支付过期订单有 {} 个",payOrders.size());
        if (CollUtil.isEmpty(payOrders)) {
            return;
        }
        // 更改订单信息，返还商品库存
        payOrders.forEach(payOrder -> {
            // 如果是商品订单需要归还商品库存，如果是vip订单直接关闭
            if(payOrder.getOrderType().equals(SHOPPING_ORDER)){
                // 通过订单id获取订单详情
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>()
                        .eq("o_id", payOrder.getId()));
                // 对于未支付的订单，归还商品的库存,并且修改已售的数量
                if(!orderDetails.isEmpty()){
                    orderDetails.forEach(detail -> {
                        ProductKind productKind = productKindMapper.selectById(detail.getKId());
                        productKind.setStock(productKind.getStock() + detail.getNum());
                        productKind.setSold(productKind.getSold() - detail.getNum());
                        productKindMapper.updateById(productKind);
                    });
                }
            }
            payOrder.setTradeState(StatusEnum.CLOSED.getCode());
            payOrderMapper.updateById(payOrder);
        });
    }



}